<template>
  <div class="app-container">
    <!--<div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="年月">
          <el-date-picker
            v-model="searchParam.yearMonthPlan"
            type="month"
            placeholder="请选择年月"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="材料">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请选择材料"
            clearable
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="resetMaterial"> 清除 </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="beforeGetTableList">
            <i-ep-search />
            展示
          </el-button>
        </el-form-item>
      </el-form>
    </div>-->

    <el-card shadow="never" class="table-container">
      <template #header>
        <!--<el-button
          class="ml-3"
          @click="
            useDownload(
              '/mes/mesplanmonthrawmaterial/export',
              '物料需求计划',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
        <el-button type="primary" plain @click="synchronizeData()"
          >同步最新数据</el-button
        >-->
        <el-button type="primary" plain @click="returnPlanMonth()"
          >返回</el-button
        >
        <el-button
          class="ml-3"
          @click="
            useDownload(
              '/mes/mesplanmonth/exportStat',
              '月度生产计划统计',
              selectDataStat,
              true,
              '.xls'
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <!-- 导入计划 -->
      <ImportExcel ref="weekImportRef" />

      <!-- objectSpanMethod方法，objectSpanMethod(param, 3, 7)
      参数3 代表三行合并
      参数13 代表从第13 + 1 列开始取消合并 -->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        element-loading-text="数据准备中，请稍后..."
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :span-method="(param) => objectSpanMethod(param, 0, 0)"
        :header-cell-style="{ textAlign: 'center' }"
        @sort-change="onTableSortChanged"
        class="dataTable"
      >
        <el-table-column width="70" label="序号" align="center" fixed>
          <template #default="{ $index, row }">
            <span v-if="row.id !== '-999'">{{ $index + 1 }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          label="材料名称"
          prop="materialCode"
          width="300"
          show-overflow-tooltip
          fixed
          align="left"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span v-if="row.id != -999">
              {{ row.materialName }}
            </span>
            <span class="text-[13px]" v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          label="合计"
          width="150"
          show-overflow-tooltip
          fixed
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span v-if="row.id != -999">
              {{
                row.listPlanActual
                  .reduce((acc, item) => {
                    return acc + (item.planStove || 0);
                  }, 0)
                  .toLocaleString("en-US", {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  })
              }}
            </span>
            <span class="text-[13px]" v-else></span>
          </template>
        </el-table-column>

        <!--<el-table-column
          label="总套数"
          prop="allSetNumber"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="P/M"
          prop="pm"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            {{ row.pm }}
          </template>
        </el-table-column>-->
        <el-table-column
          v-for="(dayItem, dayIndex) in intervalDayList"
          :key="dayIndex"
          :label="`${dayItem.date}\n${dayItem.week}`"
          min-width="85"
          align="right"
        >
          <template
            #default="{
              row,
              detailIndex = row.listPlanActual.findIndex(
                (item) => getMonthAndDay(item.requireDate) === dayItem.date
              ),
            }"
          >
            <div class="padding012" style="height: 30px">
              <!--:style="{
                backgroundColor:
                  inConsistentOne(row, detailIndex) == ''
                    ? ''
                    : inConsistentOne(row, detailIndex),
              }"
              @click="updateColour(row.details[detailIndex])"-->
              {{
                row.listPlanActual[detailIndex]?.planStove.toLocaleString(
                  "en-US",
                  { minimumFractionDigits: 2, maximumFractionDigits: 2 }
                )
              }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增物料弹窗 -->
    <plan-purchase-demand-add-dialog
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :endDate="addGoodsDialog.endDate"
      :beginDate="addGoodsDialog.beginDate"
      @reset-table="getTableList(0)"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 材料详情 -->
    <plan-material-dialog
      :visible="addNewDialog.visible"
      :title="addNewDialog.title"
      :materialId="addNewDialog.materialId"
      :data="addNewDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 预留 -->
    <plan-require-goods-add-dialog
      :visible="addGoodsDialog.visible"
      :title="addGoodsDialog.title"
      :id="addGoodsDialog.id"
      :cellId="addGoodsDialog.cellId"
      :endDate="addGoodsDialog.endDate"
      :beginDate="addGoodsDialog.beginDate"
      :data="addGoodsDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="addGoodsDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 计划模数修改 -->
    <plan-feedback-info-dialog
      :visible="feedbackDialog.visible"
      :title="feedbackDialog.title"
      :cellId="feedbackDialog.cellId"
      :demandStatus="feedbackDialog.demandStatus"
      :endDate="feedbackDialog.endDate"
      :begirate="feedbackDialog.beginDate"
      :data="feedbackDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="feedbackDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table ref="uploadErrorRef" :errorDataList="errorDataList" />

    <!--物料选择-->
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
  </div>
</template>

<script setup lang="ts">
import { SearchInterface, TableResultObject } from "./utilejs/interface";
import {
  resolveSearchData,
  objectSpanMethod,
  getDaysByMonth,
  getNextMonth,
} from "./utilejs/index";
import { filterOrder } from "@/utils/commonHooks";
import request from "@/utils/request";
import { useDownload } from "@/utils/useTable";
import { useRoute } from "vue-router";
import router from "@/router";
const route = useRoute();
defineOptions({
  name: "MESMESPLANMONTHSTATISTICS1",
  inheritAttrs: false,
});
const yearMonthPlan = ref(route.query.yearMonthPlan || "");
// 初始化搜索参数数据
const searchParam = reactive<SearchInterface>({
  materialId: "",
  materialCode: "",
  yearMonthPlan: yearMonthPlan.value,
});
// 点击搜索按钮后被保存的搜索数据
const searchedParam = reactive<SearchInterface>({
  materialId: "",
  materialCode: "",
  yearMonthPlan: getCurrentMonth(),
});

// 搜索时间变化后处理函数
const intervalDayList = ref<any[]>([]);

// 行复选框选中后处理
const ids = ref<string[]>([]);
const dataTableRef = ref();
// 表格选择
const totalMultipleSelection: any = ref([]);
function handleSelectionChange(selection: TableResultObject[]) {
  ids.value = selection.map((item: TableResultObject) => item.id);
  totalMultipleSelection.value = selection;
}

// 开始展示逻辑处理
const loading = ref(false);
const tableData = ref([]);
const selectDataStat = ref([]);
// 点击展示之前
function beforeGetTableList() {
  if (!searchParam.yearMonthPlan) {
    ElMessage.error("请选择计划月");
    return;
  }
  getTableList(1);
}

// 点击展示之后
async function getTableList(isReset = 0) {
  // isReset为 1 加载刷新、0 无感知刷新
  if (isReset === 1) {
    dataTableRef.value.setScrollTop(0);
    loading.value = true;
  }
  const { data }: any = await request({
    url: "/mes/mesplanmonth/queryByStat",
    method: "post",
    data: isReset === 0 ? toRaw(searchedParam) : toRaw(searchParam),
  }).catch(() => {});
  // 储存被搜索条件
  Object.assign(searchedParam, {
    ...toRaw(searchParam),
  });
  // 时间处理
  intervalDayList.value = getDaysByMonth(searchParam.yearMonthPlan);
  //获取下个月前七天
  // let yearMonthPlan = getNextMonth(searchParam.yearMonthPlan);
  // let nextIntervalDayList = getDaysByMonth(yearMonthPlan);
  // for (let i = 0; i < 7; i++) {
  //   intervalDayList.value.push(nextIntervalDayList[i]);
  // }
  // 数据处理
  selectDataStat.value = data;

  console.log(selectDataStat);
  tableData.value = resolveSearchData(data);
  loading.value = false;
}

// 监听表格后台排序方法
const initParam = reactive({ sort: {} });
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };

  getTableList(1);
}

// 新增物料弹窗及操作逻辑
const addDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
function changeVisible(value: boolean) {
  addDialog.visible = value;
  addGoodsDialog.visible = value;
  feedbackDialog.visible = value;
  addNewDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    addGoodsDialog.data = {};
    addGoodsDialog.cellId = "";
    addGoodsDialog.id = "";
    feedbackDialog.data = {};
    feedbackDialog.cellId = "";
    addNewDialog.data = {};
  }
}

// 新增要货弹窗及操作逻辑
const addGoodsDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  id: "",
});

// 反馈信息确认弹窗及操作逻辑
const feedbackDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  demandStatus: null,
});

// 导入计划
const weekImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);

// 新增物料（新版）弹窗及操作逻辑
const addNewDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  materialId: "",
});
const planMaterial = (row) => {
  const object = {
    visible: true,
    title: "材料详情",
    materialId: row.materialId,
  };
  Object.assign(addNewDialog, { ...object });
};

function getMonthAndDay(date: any) {
  let month = date.slice(5, 7);
  let day = date.slice(8, 10);
  return month + "/" + day;
}
const calculationPlan = async () => {
  ElMessageBox.confirm("确定对已选择数据进行智能计算吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mes/mesplanmonth/calculationPlan",
        method: "post",
        data: totalMultipleSelection.value,
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "计算完成",
        });
      }
      await getTableList(1);
    })
    .catch(() => {});
};
const updateColour = (detail: any) => {
  if (detail?.status === 1) {
    ElMessageBox.confirm("是否确认?", "警告", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        detail.status = 2;
        const res: any = await request({
          url: `/mes/mescoredemanddetail/save`,
          method: "post",
          data: detail,
        });
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "确认成功",
          });
          getTableList(1);
        }
      })
      .catch(() => {});
  }
};
//材料选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.materialId = data.id;
    searchParam.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  searchParam.materialId = "";
  searchParam.materialCode = "";
};
//同步
const synchronizeData = async () => {
  await ElMessageBox.confirm("请确认是否同步最新数据！", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 开启按钮加载
        instance.confirmButtonLoading = true;
        await request({
          url: `/mes/mesplanmonthrawmaterial/synchronous`,
          method: "post",
          data: { yearMonthPlan: searchParam.yearMonthPlan },
        })
          .then((res) => {
            ElMessage({
              type: res.code == 200 ? "success" : "error",
              message: res.code == 200 ? "同步成功" : res.message,
            });
          })
          .catch((res) => {
            done();
          });
        getTableList();
      }
      done();
    },
  });
};
// 获取当前日期yyyy - mm
function getCurrentMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ("0" + (now.getMonth() + 1)).slice(-2);
  return year + "-" + month;
}

onMounted(() => {
  beforeGetTableList();
});
function returnPlanMonth() {
  if (searchParam.yearMonthPlan) {
    router.push({
      path: "/mes/mesplanmonth",
    });
  }
}
</script>

<style lang="scss" scoped>
// 所有表格样式
:deep(.dataTable) {
  .el-table__body td.el-table__cell {
    padding: 0;
    .can_edit_cell:hover {
      color: #409eff !important;
    }
  }
  .cell {
    padding: 0;
    white-space: pre-wrap;
  }
  .padding012 .cell {
    padding: 0 12px !important;
  }
  td.el-table__cell .cell > :first-child {
    padding: 3px 12px;
  }

  .el-scrollbar__wrap {
    max-height: calc(100vh - 342px);
    overflow-y: scroll;
  }

  .seltAllbtnDis .cell {
    visibility: hidden;
  }
  .el-table__empty-block {
    height: 120px !important;
  }
  .el-table__row {
    height: 50px !important;
  }
}

:deep(.el-table--border th.bg-free) {
  background-color: rgb(239.8, 248.9, 235.3) !important;
}

// 红色标识
.c-red-font {
  background-color: #fef1f1 !important;
  span {
    // color: lightcoral;
    color: brown !important;
  }
}

// 绿色标识
.c-green {
  background: #55efc4 !important;
  span {
    color: #2f4f4f !important;
  }
}

.cellNumber:hover {
  text-decoration: underline;
}
</style>
